package com.iraeta.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iraeta.common.Result;
import com.iraeta.controller.BaseController;
import com.iraeta.entity.main.CustomOrg;
import com.iraeta.entity.main.Role;
import com.iraeta.entity.main.SysOrg;
import com.iraeta.entity.main.TreeNode;
import com.iraeta.service.sys.ISysOrgService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController(value = "OrgController")
@RequestMapping("sys/org")
public class OrgController extends BaseController {
    @Resource
    ISysOrgService orgService;

    @RequestMapping("orgtreedata")
    public String orgTreeData(@RequestBody JSONObject jo){
        Integer orgId =  jo.getInteger("orgId") == null ? CustomOrg.root : jo.getInteger("orgId");
        List<TreeNode> roleList = orgService.listChildrenOrg(orgId);
        return this.success(roleList);
    }

    @RequestMapping("getorg")
    public String getOrg(@RequestBody JSONObject paramJb){
        int orgId = paramJb.getIntValue("id");
        SysOrg sysOrg = orgService.getOrg(orgId);
        return JSON.toJSONString(Result.success(sysOrg));
    }

    @RequestMapping("addeditorg")
    public String addOrg(@RequestBody JSONObject paramJb){
        int orgId = paramJb.getIntValue("id");
        SysOrg sysOrg = orgId == 0 ? new SysOrg() :  orgService.getOrg(orgId);
        this.mapJsonToObj(paramJb, sysOrg);
        if(orgId == 0){
            orgService.addOrg(sysOrg);
        }else {
            orgService.updateOrg(sysOrg);
        }
        return JSON.toJSONString(Result.success());
    }

    @RequestMapping("deleteorg")
    public String deleteOrg(@RequestBody JSONObject paramJb){
        int orgId = paramJb.getIntValue("id");
        orgService.deleteOrg(orgId);
        return JSON.toJSONString(Result.success());
    }
}
